<template>
    <div class="payin">
        <section class="order-main-header">
            <mt-header title="充值">
            <mt-button  icon="back" slot="left" @click="handleClose()"></mt-button>
            <a @click="addressChange()"  slot="right" ><img src="../../assets/address.png"></a>
            </mt-header>
        </section>
      <section class="payin-card otc">
          <div class="choose-coin">
              <span>选择币种</span>
              <span class="select" @click="qrcodeVisible()">{{coinAddressChoose.name}}  <img  class="rotate" src="../../assets/my/right.png"></span>
          </div>
          <div class="line-coin" v-if="coinAddressChoose.name=='USDT'">
              <span class="type">链类型</span>
              <div class="flex-start"  >
                  <div class="coin "  >{{coinAddressChoose.chainName}}</div>
              </div>
          </div>
          <div class="payin-content">
              <div class="code flex-all-center" id="qrcode-pay">
                 <div id="qrcode" ref="qrcode"></div>             
              </div>
             <div class="btn flex-all-center">
                 <button  @click="downPay()">保存二维码至相册</button>
             </div>
             <div class="address">
                 <p>充币地址</p>
                 <b>{{coinAddress}}</b>
             </div>
               <div class="btn flex-all-center">
                 <button @click="copy(coinAddress)">复制</button>
             </div>
             <div class="address" v-if="coinVisible">
                 <p>标签</p>
                 <b>{{coinVisibleValue}}</b>
             </div>
               <div class="btn flex-all-center" v-if="coinVisible">
                 <button @click="copy(coinVisibleValue)">复制</button>
             </div>
             <div class="payin-titel">
                 <p>禁止向{{coinAddressChoose.name}}地址充值除{{coinAddressChoose.name}}之外的资产，任何充入{{coinAddressChoose.name}}地址的非{{coinAddressChoose.name}} 资产将不可找回。</p>
                 <p> 使用{{coinAddressChoose.name}}地址充值需要{{coinAddressChoose.confirmations}}个区块确认才能到账，入账时间一般在5分钟-30分钟左右。</p>
             </div>
          </div>
    </section>
      <mt-actionsheet
        :actions="actions"
       v-model="sheetVisible">
        </mt-actionsheet>
    </div>
</template>
<script>
import axios from 'axios'
import QRCode from 'qrcode2'
import { Actionsheet } from 'mint-ui';
import { Toast } from 'mint-ui';
import html2canvas from 'html2canvas';
export default {
    name:'',
   data(){
         return {
             coinList:'',
             coinAddress:'',
             sheetVisible:false,
               actions: [],
           coinAddressChoose:'',
           qrcodeInfo:'',
           coinVisible:false,
           coinVisibleValue:'',
           payinId:'',
           paramsByCoin:'',
           qrcodeValue:""
         }
    },
    mounted() {
        this.$http.post('v1/session?'+ new Date().getTime(),).then((res)=>{
            this.sessionData=res.data.data;
        })
        this.getCoinList();
        this.payinId=this.$store.state.payin;
        //this.getParamsByCoin();
       
    },
    methods: {  
   createDownload(url) {
    /*设置下载路径*/
    let loadUrl = 'https://biplush.oss-ap-southeast-1.aliyuncs.com/'+url;
    //设置保存路径
       var relativePath =  "_downloads/" + '/upload/others/201912082107027_BxNIUJJ.png';
    //alert(relativePath);
    plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
        // Toast("文件已存在," );
        delFile(relativePath)
    }, function(e) {
      //  alert("文件不存在,联网下载=" + relativePath);
        setImgFromNet(loadUrl, relativePath);
    });
 /*给图片标签<img>设置本地图片
         * imgId 图片标签<img>的id
         * relativePath 本地相对路径 例如:"_downloads/logo.jpg"
         */
        function setImgFromLocal(imgId, relativePath) {
                //本地相对路径("_downloads/logo.jpg")转成SD卡绝对路径("/storage/emulated/0/Android/data/io.dcloud.HBuilder/.HBuilder/downloads/logo.jpg");
                var sd_path = plus.io.convertLocalFileSystemURL(relativePath);
            }
    function setImgFromNet(loadUrl, relativePath) {
        //创建下载任务
        var dtask = plus.downloader.createDownload(loadUrl, {filename:relativePath}, function(d, status) {
            if(status == 200) {
                //下载成功
                   //下载成功
                 plus.storage.setItem("relativePath", relativePath); //存储db文件路径名
                  setImgFromLocal('', d.filename);
                plus.gallery.save(relativePath,function() {//保存到相册方法
            Toast('已保存,请到到手机相册查看');
            }, function() {
            Toast('保存失败，请重试！');
            });
            } else {
                //下载失败,需删除本地临时文件,否则下次进来时会检查到文件已存在
              //  Toast("下载失败=" + status + "==" + relativePath);
                if(relativePath != null)
                    delFile(relativePath);
            }
        });
        //启动下载任务
        dtask.start();
    }
    /*删除指定文件*/
    function delFile(relativePath) {
        plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
            entry.remove(function(entry) {
                setImgFromNet(loadUrl, relativePath);
            }, function(e) {
            });
        });
    }
},
        addressChange(){
              this.$router.push({
          path: `/finance/payinRecord/${'?id='+this.coinAddressChoose.id+'&index='+this.coinAddressChoose.name}`
        });
        },
         qrcode () {
              var that = this;
           var  qrcode=this.qrcodeInfo = new QRCode('qrcode', {
                width: 368,
                height: 368, // 高度
            })
            qrcode.clear(); // clear the code.
           qrcode.makeCode( this.coinAddress); // make another code.
          
          let shareContent = document.getElementById('qrcode-pay'); //需要截图的包裹的（原生的）DOM 对象
      var   canvas = document.createElement("canvas"), //创建一个canvas节点
           scale = 1; //定义任意放大倍数 支持小数
       canvas.width = "368"; //定义canvas 宽度 * 缩放
       canvas.height = "368"; //定义canvas高度 *缩放
      let opts = {
            scale: scale, // 添加的scale 参数
           canvas: canvas, //自定义 canvas
           logging: false, //日志开关，便于查看html2canvas的内部执行流程
           width: "368", //dom 原始宽度
           height: "368",
           useCORS: true
       };
               html2canvas(shareContent, opts).then(function(canvas) {
                   that.qrcodeValue= canvas.toDataURL("image/png", 1.0);
                }).catch(function (reason) {
                });
        },
         dataURLtoFile(dataurl, filename = 'file') {
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let suffix = mime.split('/')[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            })
            },
          copy(data) {  
                    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS
              var input = document.createElement("input");
              input.setAttribute('readonly', 'readonly');
             var message=data;
            input.value = message;
            document.body.appendChild(input);
            input.select();
            input.setSelectionRange(0, input.value.length), document.execCommand('Copy');
            input.style.display='none';
              input.className = 'oInput';
            document.body.removeChild(input);
             input.focus(); 
                 Toast("复制成功");
            }else{
        var Url2=data;
          var oInput = document.createElement('input');
          oInput.setAttribute('readonly', 'readonly');
        oInput.value = Url2;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.className = 'oInput';
        oInput.style.display='none';
        Toast("复制成功");
        }
        },
         downPay(e){
             let that=this;
            //必须同源才能下载
                // var alink = document.createElement("a");
                // alink.href = this.qrcodeInfo._el.lastChild.currentSrc;
                // alink.download = "pic"; //图片名
                // alink.click();
            
                // var shareContent= this.qrcodeInfo._el.firstChild;
                console.log(this.qrcodeValue)
             var imgFile = this.dataURLtoFile(this.qrcodeValue); 
            let formData = new FormData()
                        formData.append('img',imgFile,imgFile.name)
                        formData.append('type',1);
                        this.$http.upload('/v1/account/upload.html',formData,{
                            headers: { 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7j36XuEUfKHvtxmd' }
                        }).then(res=>{
                       res = res.data
                            if(res.code == 200){
                        this.createDownload(res.data);
                        }
                        }).catch(err=>{
                            console.warn(err)
                        })
            },
        qrcodeVisible(){
            this.sheetVisible=true;
        },
        getCoinList(){
              this.$http.post('v1/coinList').then((res)=>{
                  let data=res;
                  this.coinList=data.data.data;
                this.actions= this.coinList;
                   for (let i = 0; i <  this.coinList.length; i++) {
                        if(this.$store.state.payin){
                       if(this.$store.state.payin==this.coinList[i].id){
                             this.coinAddressChoose=this.coinList[i];
                        }
                       }else{
                             this.coinAddressChoose=this.coinList[0];
                       }
                          this.actions[i]["name"]=this.coinList[i].name;
                           this.actions[i]["method"]=this.coinChange;
                   }
           this.getCoinAddress(this.coinList[0]);
        })
    },
    coinChange(val){
        this.$refs.qrcode.innerHTML = ''
       this.coinAddressChoose=val;
       this.$http.get('v1/account/getCoinAddress?'+'symbol'+'='+val.id+'&create='+1+'').then((res)=>{
           this.coinAddress=res.data.data;
             this.qrcode();
              if(val.name=='EOS' ||val.name=='XRP'){
                    this.coinVisibleValue = data.split(",")[1];
                    this.coinVisible=true;
             }
        })
    },
    getCoinAddress(data){
              this.$http.get('v1/account/getCoinAddress?'+'symbol'+'='+data.id+'&time='+Math.random()+'').then((res)=>{
           this.coinAddress=res.data.data;
           if(this.coinAddress){
               this.qrcode();
           }
        })
    },
        　　handleClose(){
                this.$router.go(-1);
            },
    }
}
</script>
<style lang="less" scoped>
.payin-content{
    .code{
        #qrcode{
            border: 2px solid #fff;
            width:368px;
        height:364px;
        }
        margin-bottom: 40px;
        margin-top: 40px;
    }
    .btn button{
        width:600px;
    height:88px;
    background:rgba(82,152,241,1);
    border-radius:10px;
    color: #FFFFFF;
    font-size:28px;
    }
    .address{
        font-size:28px;
        color: #E0E0F9;
        height: 150px;
        line-height: 80px;
        padding-left: 50px;
        margin-top: 20px;
        margin-bottom: 20px;
    }
    .address b{
        text-align: center;
        width: 100%;
    }
    .payin-titel{
      p{
            line-height:38px;
            margin-bottom: 30px;
      }
        font-size:24px;
        color: #E0E0F9;
        padding: 20px 40px 20px 40px;
    }
}
.choose-coin{
    .select{
        float: right;
        padding-right: 30px;
    }
    span{
        color: #8686C0;
        padding-left: 30px;
    }
}
.line-coin {
    padding-left: 30px;
    .type{
        height:100px;
        font-size:28px;color:rgba(224,224,249,1);
        line-height:100px;
    }
    .coin{
        width:180px;
        height:68px;
        border-radius:4px;
        border:2px solid rgba(51,129,255,1);
        text-align: center;
        line-height: 68px;
        margin-right: 40px;
         color: #E0E0F9;
    }
    .active{
        color: #3381FF;
        border:2px solid rgba(51,129,255,1);
    }
    .no-active{
        color: #E0E0F9;
        border:2px solid rgba(224,224,249,1);
    }
}
.flex-center{
    display: flex;
    align-items: center;
}
.flex-start{
    display: flex;
    align-items: start;
}
.flex-all-center{
    display: flex;
    align-items: center;
    justify-content: center;
}
.mint-header{
    height: 100px;
    font-size: 32px;
    background-color: #161736;
    color: #E0E0F9
}
.rotate{
    transform:rotate(-180deg);
-webkit-transform:rotate(-180deg);
-moz-transform:rotate(-180deg);
-o-transform:rotate(-180deg);
-mz-transform:rotate(-180deg);
width: 30px;
height: 30px;
}
#qrcode-pay{
    width: 368px;
    margin: 40px auto;
}
</style>